#include <stdio.h>
#include <stdlib.h>
#include <time.h>

static int g_count;

// get random num between 0 and (num-1)
int getRand(int num)
{
    g_count++;
    if(num <= 0) return 0;

    return rand() % num;    
}

void swap(int *a, int *b);
void quicksort(int *array, int maxlen, int begin, int end);
void genrate();

void genrate()
{
    int i, tmp;
    int red[33];
    for(i = 0; i < 33; i++)
        red[i] = i + 1;

    for(i = 0; i < 6; i++)
    {
        tmp = getRand(33 - i);
        swap(&red[tmp], &red[32 - i]);
    }
    tmp = getRand(16) + 1;
    quicksort(red, 33, 27, 32);
    printf("%2d %2d %2d %2d %2d %2d [%d]\n",
        red[27], red[28], red[29], red[30], red[31], red[32], tmp);
}

int main(int argc, char *argv[])
{
    int i;
    g_count = 0;
    srand((unsigned)time(NULL));
    for(i = 0; i < 10; i++)
        genrate();

    printf("g_count = %d\n", g_count);

    return 0;
}

void quicksort(int *array, int maxlen, int begin, int end)
{
    int i, j;

    if(begin < end) {
        i = begin + 1;
        j = end;

        while(i < j) {
            if(array[i] > array[begin]) {
                swap(&array[i], &array[j]);
                j--;
            }
            else {
                i++;
            }
        }

        if(array[i] >= array[begin]) {
            i--;
        }

        swap(&array[begin], &array[i]);

        quicksort(array, maxlen, begin, i);
        quicksort(array, maxlen, j, end);
    }
}

void swap(int *a, int *b)
{
    int temp;

    temp = *a;
    *a = *b;
    *b = temp;
}
